﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TienIch.Utils;
using TienIch.Model;
using TienIch.Business;
using DevExpress.XtraEditors;

namespace TienIch
{
    public partial class frmShowStaff : FormBase
    {
        #region Variables
        public UsersModel Model = new UsersModel();
        #endregion

        #region Contructors and Load
        public frmShowStaff()
        {
            InitializeComponent();
        }

        private void frmShowStaff_Load(object sender, EventArgs e)
        {
            loadCombo();

            if (Model.ID != 0)
            {
                txtBankAccount.Text = Model.BankAccount;
                txtBHXH.Text = Model.BHXH;
                txtBHYT.Text = Model.BHYT;
                dtpBirthOfDate.EditValue = Model.BirthOfDate;
                txtCMTND.Text = Model.CMTND;
                txtCode.Text = Model.Code;
                cboDepartment.SelectedValue = Model.DepartmentID;
                txtEmail.Text = Model.Email;
                txtEmailCom.Text = Model.EmailCom;
                txtFullName.Text = Model.FullName;
                txtTelephone.Text = Model.HandPhone;
                txtHomeAddress.Text = Model.HomeAddress;
                txtJobDescription.Text = Model.JobDescription;
                txtLoginName.Text = Model.LoginName;
                txtMST.Text = Model.MST;
                txtPasswordHash.Text = MD5.DecryptPassword(Model.PasswordHash);
                txtPosition.Text = Model.Position;
                txtQualifications.Text = Model.Qualifications;
                cboSex.SelectedIndex = Model.Sex;
                dtpStartWorking.EditValue = Model.StartWorking;
                pictureBox1.ImageLocation = Model.ImagePath;
                cboStatus.SelectedIndex = Model.Status;
                lookUpEdit1.EditValue = Model.UserGroupID;
                if (txtLoginName.Text != "")
                {
                    chkHasUser.Checked = true;
                }
            }
        }
        #endregion

        #region Functions

        void loadCombo()
        {
            DataTable tbl = Easy.Select(@"SELECT ID,Name FROM Department WITH(NOLOCK) ORDER BY Name");
            if (tbl == null)
            {
                return;
            }
            Easy.PopulateCombo(cboDepartment, tbl.Copy(), "Name", "ID", "-- Phòng ban --");
            DataTable tblPerson = Easy.Select("Select ID, Code, Name from UserGroup a with(nolock)");
            Easy.PopulateCombo(lookUpEdit1, tblPerson.Copy(), "Name", "ID", "-- Chọn nhóm --");
        }

        private bool ValidateForm()
        {
            if (txtCode.Text.Trim() == "")
            {
                XtraMessageBox.Show("Xin hãy điền Mã nhân viên.", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            else
            {
                DataTable dt;
                if (Model.ID > 0)
                {
                    dt = Easy.Select("select Code from Users where Code = '" + txtCode.Text.Trim() + "' and ID <> " + Model.ID);
                }
                else
                {
                    dt = Easy.Select("select Code from Users where Code = '" + txtCode.Text.Trim() + "'");
                }
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        XtraMessageBox.Show("Mã nhân viên này đã được sử dụng!", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        return false;
                    }
                }
            }
            if (txtFullName.Text.Trim() == "")
            {
                XtraMessageBox.Show("Xin hãy điền Tên nhân viên.", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (chkHasUser.Checked)
            {
                if (txtPasswordHash.Text.Trim() == "")
                {
                    XtraMessageBox.Show("Xin hãy điền Mật khẩu.", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }
                if (txtLoginName.Text.Trim() == "")
                {
                    XtraMessageBox.Show("Xin hãy điền Tên đăng nhập.", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }
                else
                {
                    DataTable dt;
                    if (Model.ID > 0)
                    {
                        dt = Easy.Select("select LoginName from Users where LoginName = '" + txtLoginName.Text.Trim() + "' and ID <> " + Model.ID);
                    }
                    else
                    {
                        dt = Easy.Select("select LoginName from Users where LoginName = '" + txtLoginName.Text.Trim() + "'");
                    }
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            XtraMessageBox.Show("Tên đăng nhập này đã được sử dụng!", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return false;
                        }
                    }
                }
            }
           
            if (Easy.ToInt(cboDepartment.SelectedValue) <=0)
            {
                XtraMessageBox.Show("Làm ơn nhập phòng ban!", Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            return true;
        }

        /// <summary>
        /// Load bằng cấp nhân viên
        /// </summary> 
        void loadDegree()
        {
            DataTable dt = Easy.Select("Select * from Degrees WITH(NOLOCK) WHERE UserID = " + Model.ID);
            grdData.DataSource = dt;
            grvData.BestFitColumns();
        }
        #endregion

        #region Events
        private void btnSave_Click(object sender, EventArgs e)
        {

            grvData.FocusedRowHandle = -1; ProcessTransaction pt = new ProcessTransaction();
            pt.OpenConnection();
            pt.BeginTransaction();
            try
            {
                if (!ValidateForm())
                    return;              

                Model.BankAccount = txtBankAccount.Text.Trim();
                Model.BHXH = txtBHXH.Text.Trim();
                Model.BHYT = txtBHYT.Text.Trim();
                try
                {
                    Model.BirthOfDate = Easy.ToDate(dtpBirthOfDate.EditValue.ToString());
                }
                catch
                {
                    Model.BirthOfDate = DateTime.Now;
                }

                Model.CMTND = txtCMTND.Text.Trim();
                Model.Code = txtCode.Text.Trim();
                Model.DepartmentID = Easy.ToInt(cboDepartment.SelectedValue);
                Model.Email = txtEmail.Text.Trim();
                Model.EmailCom = txtEmailCom.Text.Trim();
                Model.FullName = txtFullName.Text;
                Model.HandPhone = txtTelephone.Text;
                Model.HomeAddress = txtHomeAddress.Text;
                Model.JobDescription = txtJobDescription.Text.Trim();
                Model.MST = txtMST.Text.Trim();
                Model.Position = txtPosition.Text;
                Model.Qualifications = txtQualifications.Text.Trim();
                Model.Sex = cboSex.SelectedIndex;
                Model.UserGroupID =Easy.ToInt(lookUpEdit1.EditValue);
                try
                {
                    Model.StartWorking = Easy.ToDate(dtpStartWorking.EditValue.ToString());
                }
                catch
                {
                    Model.StartWorking = DateTime.Now;
                }

                Model.ImagePath = pictureBox1.ImageLocation;
                Model.Status = cboStatus.SelectedIndex;

                if (chkHasUser.Checked)
                {
                    Model.LoginName = txtLoginName.Text.Trim();
                    Model.PasswordHash = MD5.EncryptPassword(txtPasswordHash.Text.Trim());
                }
                else
                {
                    Model.LoginName = "";
                    Model.PasswordHash = "";
                }

                if (Model.ID == 0)
                {
                    Model.CreatedDate = Easy.GetSystemDate();
                    Model.CreatedBy = Global.AppUserName;
                    Model.UpdatedDate = Model.CreatedDate;
                    Model.UpdatedBy = Global.AppUserName;
                    Model.ID = (int)pt.Insert(Model);
                }
                else
                {
                    Model.UpdatedDate = Easy.GetSystemDate();
                    Model.UpdatedBy = Global.AppUserName;
                    pt.Update(Model);
                }
                pt.CommitTransaction();
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, Easy.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {                
                pt.CloseConnection();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chkHasUser_CheckedChanged(object sender, EventArgs e)
        {
            txtPasswordHash.Enabled = txtLoginName.Enabled = chkHasUser.Checked;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog()==DialogResult.OK)
            {
                pictureBox1.ImageLocation = ofd.FileName;
            }
        }

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (TabControlUser.SelectedTabPage == tabPageBangCap)
            {
                btnAddDegree.Enabled = btnEditDegree.Enabled = btnDelDegree.Enabled = Model.ID != 0;
                if (Model.ID != 0)
                {
                    loadDegree();
                }
            }
        }      

        private void btnAddDegree_Click(object sender, EventArgs e)
        {
            //frmDegree frm = new frmDegree();
            //frm.UserID = Model.ID;
            //if (frm.ShowDialog()==DialogResult.OK)
            //{
            //    loadDegree();
            //}
        }

        private void btnEditDegree_Click(object sender, EventArgs e)
        {
            //int id = TextUtils.ToInt(grvData.GetFocusedRowCellValue(colID));
            //if (id == 0) return;
            //frmDegree frm = new frmDegree();
            //frm.UserID = Model.ID;
            //frm.Model = (DegreesModel)DegreesBO.Instance.FindByPK(id);
            //if (frm.ShowDialog() == DialogResult.OK)
            //{
            //    loadDegree();
            //}
        }

        private void btnDelDegree_Click(object sender, EventArgs e)
        {
            //DialogResult result = XtraMessageBox.Show("Bạn có thực sự muốn xóa bằng cấp này?", TextUtils.Caption, MessageBoxButtons.YesNo);
            //if (result==DialogResult.Yes)
            //{
            //    int id = TextUtils.ToInt(grvData.GetFocusedRowCellValue(colID));
            //    if (id == 0) return;
            //    DegreesBO.Instance.Delete(id);
            //    loadDegree();
            //}            
        }
        #endregion
    }
}
